<template>
  <div class="app-container">
    <Pagetitle
      :title="pageTitle.title"
      :name="pageTitle.name"
      :btnName="pageTitle.btnName"
      @btnFun="btnFun"
    ></Pagetitle>
    <div class="filter-container">
      <Row>
        <Col :md="4">
        <DatePicker
          v-model="userHistoryDate"
          type="month"
          :clearable="false"
          format="yyyy-MM"
          placeholder="完成日期"
          @on-change="search"
        ></DatePicker>
        </Col>
        <Col
          :md="20"
          class="search-btn"
        >
        </Col>
      </Row>
    </div>
    <div class="table-container">
      <div class="chart-title">
        品牌<span class="chart-subtitle">（单位：分值）</span>
      </div>
      <easyChart
        :id="'userChart'"
        :data='userReportOption'
      ></easyChart>
    </div>

    <div class="table-container">
      <div class="chart-title">
        物料<span class="chart-subtitle">（单位：数量）</span>
      </div>
      <easyChart
        :id="'userMaterial'"
        :data='materialOption'
      ></easyChart>
    </div>
    <div class="table-container">
      <Table
        stripe
        :loading="dataTable.loading"
        :border="dataTable.border"
        :columns="dataTable.columns"
        :data="dataTable.data"
      >
      </Table>

      <Row class="mtop20">
        <Col
          :md="4"
          class="flex-start-center height-30 page"
        >
        <!-- <div>
          共{{count}}条
          <Select
            v-model="limit"
            size="small"
            class="lz-select-width"
            @on-change="changePageSize(1)"
          >
            <Option
              v-for="item in pageSizeSeletc"
              :value="item.value"
              :key="item.value"
            >{{ item.label }}</Option>
          </Select>
        </div> -->
        </Col>
        <Col
          :md="12"
          class="flex-center-center height-30"
        >
        <!-- <Page
          v-if="pageshow"
          :total="count"
          :page-size="limit"
          @on-change="changePageSize"
          size="small"
          show-elevator
        /> -->
        </Col>
        <Col :md="8">
        <div class="page-size">
          <div
            class="keying-btn border-red"
            @click="downLoadExl()"
          >下载表格</div>
        </div>
        </Col>
      </Row>
    </div>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import {
  fetchStaffUserHistory,
  fetchStaffUserMaterial,
  fetchStaffUserBrand
} from "@/api/table";
import easyChart from "@/components/EasyChart";
import { Pagetitle, Model } from "@/components";
import format from "date-format";
import { getStore } from "@/utils/index";
export default {
  data() {
    return {
      pageshow: true,
      //总页码
      count: 0,
      //页码
      currentPage: 1,
      //总条数
      limit: 10,
      pageSizeSeletc: [
        {
          value: 10,
          label: "10条/页"
        },
        {
          value: 20,
          label: "20条/页"
        }
      ],
      modal1: false,
      pageTitle: {
        title: "员工报销>"
      },
      dataTable: {
        loading: false,
        border: false,
        columns: [
          {
            minWidth: 100,
            title: "姓名",
            key: "name"
          },
          {
            minWidth: 120,
            title: "完成时间",
            key: "materialCount",
            render: (h, params) => {
              return h(
                "div",
                format("yyyy-MM", new Date(params.row.finishTime))
              );
            }
          },
          {
            minWidth: 100,
            title: "职位/级别",
            key: "levelName"
          },
          {
            minWidth: 100,
            title: "组别",
            key: "categoryName"
          },
          {
            minWidth: 100,
            title: "分值",
            key: "personScore"
          }
        ],
        data: []
      },
      timeSelectValue: "1",
      timeSelect: [
        {
          value: "1",
          label: "按月份"
        }
      ],
      userHistoryDate: "",
      dateType: "month",
      searchForm: {
        startTime: "",
        endTime: ""
      },
      materialOption: {},
      materialData: {
        name: [],
        count: []
      },
      userReportOption: {},
      brandData: [],
      userInfo: {}
    };
  },
  components: {
    Pagetitle,
    Model,
    easyChart
  },
  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      this.userInfo = JSON.parse(getStore("userInfo"));
      this.pageTitle.title =
        "员工报表>" + this.userInfo.name + "(" + this.userInfo.userId + ")";
      //time是上个页面带的世界
      this.userHistoryDate =
        this.$route.query.time || format("yyyy-MM", new Date());
      this.getUserHistory();
    },
    //分页
    changePageSize(index) {
      this.currentPage = index;
      this.getUserHistory();
    },
    search() {
      this.currentPage = 1;
      this.pageshow = false;
      this.getUserHistory();
      this.$nextTick(() => {
        this.pageshow = true;
      });
    },
    async getUserHistory() {
      let start;
      let end;
      if (this.userHistoryDate !== "") {
        const nowDate = format("yyyy-MM", new Date(this.userHistoryDate));
        if (this.timeSelectValue === "3") {
          start = nowDate[0];
          end = nowDate[1];
        } else if (this.timeSelectValue === "2") {
          start = nowDate + "-01-01";
          end = nowDate + "-12-31";
        } else if (this.timeSelectValue === "1") {
          const spData = nowDate.split("-");
          start = nowDate + "-01";
          end = nowDate + "-" + this.mGetDate(spData[0], spData[1]);
        }
      }
      this.dataTable.loading = true;
      const res = await fetchStaffUserHistory({
        startTime: start,
        endTime: end,
        userId: this.userInfo.userId
      });
      const brand = await fetchStaffUserBrand({
        startTime: start,
        endTime: end,
        userId: this.userInfo.userId
      });
      const material = await fetchStaffUserMaterial({
        startTime: start,
        endTime: end,
        userId: this.userInfo.userId
      });
      this.materialData.name = [];
      this.materialData.count = [];
      material.data.forEach(item => {
        this.materialData.name.push(item.secondmaterial);
        this.materialData.count.push(item.materialCount);
      });
      this.brandData = [];
      brand.data.forEach(item => {
        const bdata = {};
        bdata.name = item.brandName;
        bdata.value = item.brandScore;
        this.brandData.push(bdata);
      });
      this.setUserMaterialOption();
      this.setUserBrandOption();
      this.dataTable.loading = false;
      this.count = res.data.length;
      this.dataTable.data = [];
      if (res.data.length > 0) {
        res.data.forEach(item => {
          const data = {};
          data.name = item.name;
          data.personScore = item.personScore;
          data.levelName = item.levelName;
          data.finishTime = item.finishTime;
          data.categoryName = item.categoryName;
          this.dataTable.data.push(data);
        });
      }
    },
    btnFun() {},
    downLoadExl() {
      const href =
        process.env.BASE_URL +
        "statement/userHistoryDownload?searchUserId=" +
        this.userInfo.userId;
      window.open(href, "_blank");
    },
    //获得月天数
    mGetDate(year, month) {
      var d = new Date(year, month, 0);
      return d.getDate();
    },
    setUserBrandOption() {
      this.userReportOption = {
        series: [
          {
            name: "品牌",
            type: "pie",
            radius: "25%",
            radius: ["50%", "60%"],
            avoidLabelOverlap: true,
            animation: false,
            labelLine: {
              //图形外文字线
              normal: {
                lineStyle: {
                  color: "#222121"
                },
                length: 35,
                length2: 150
              }
            },
            label: {
              position: "outer",
              alignTo: "labelLine",
              color: "#222121",
              formatter: "{b}: {d}%\n\n",
              padding: [0, -120], //在线上
              bleedMargin: 5
            },
            itemStyle: {
              normal: {
                color: function(params) {
                  //自定义颜色
                  var colorList = [
                    "#CB2D00",
                    "#1B6EC1",
                    "#2F86DC",
                    "#96CAFF",
                    "#FFD7CC",
                    "#FFAD96",
                    "#F98D6E",
                    "#EF6A44",
                    "#E4572F"
                  ];
                  return colorList[params.dataIndex];
                }
              }
            },
            data: this.brandData
          }
        ]
      };
    },
    setUserMaterialOption() {
      this.materialOption = {
        grid: {
          bottom: 80
        },
        xAxis: {
          type: "category",
          data: this.materialData.name,
          axisLine: {
            //x轴
            show: false
          },
          axisTick: {
            //x轴刻度线c
            show: false
          },
          splitLine: {
            //网格线
            show: false
          },
          axisLabel: {
            interval: "auto",
            rotate: "45",
            fontSize: 10
          }
        },
        yAxis: [
          {
            show: false,
            axisLine: {
              //x轴
              show: false
            },
            axisTick: {
              //x轴刻度线
              show: false
            },
            splitLine: {
              //网格线
              show: false
            }
          }
        ],
        series: [
          {
            data: this.materialData.count,
            type: "bar",
            barMaxWidth: 12,
            label: {
              normal: {
                show: true,
                position: "top",
                color: "#5B5959"
              }
            }
          }
        ]
      };
    }
  },
  computed: {
    ...mapGetters(["userId", "rolesId"])
  }
};
</script>
<style lang="less" scoped>
@import "~@/styles/mixin";
.clear-search {
  margin-left: 10px;
}
.group-user {
  color: @default-color;
  font-family: SourceHanSansCN-Medium, SourceHanSansCN;
  font-weight: 500;
}
.warning {
  margin-left: 30px;
  color: @primary-color;
}
.total-score {
  font-size: 16px;
  color: @default-color;
  margin-bottom: 20px;
  font-family: SourceHanSansCN-Medium, SourceHanSansCN;
  span {
    color: @primary-color;
  }
}
.filter-container {
  border-radius: 8px;
  margin-top: 15px;
  background-color: #fff;
  padding: 20px;
}
.date-picker {
  width: 208px;
  line-height: 30px;
  margin-left: 10px;
}
.search-btn {
  display: flex;
  justify-content: flex-end;
}
</style>